$(function () {
// 下拉

    var lvideoUrl="";
    var screenShot= ""
    function initWebuploader() {
        var roomVideo = WebUploader.create({

            // 选完文件后，是否自动上传。
            auto: true,

            // swf文件路径
            swf: '/js/Uploader.swf',

            // 文件接收服务端。
            server: '/file/upload',
            fileNumLimit: 2,
            duplicate:true,
            chunked: true,
            chunkSize: 2 * 1024 * 1024,
            threads: 1,
            pick: {
                id: '#video-url',
                label: '上传视频'
            },
            accept: {
                title: '视频上传',
                extensions: 'mp4',
                mimeTypes: 'video/*,audio/*,application/*',
            }
        });


        roomVideo.on( 'fileQueued', function( file ) {
            // console.log('fileQueued')
            $(".video-msg").text("加入文件")
        })

        roomVideo.on( 'uploadSuccess', function( file ,response) {
            // console.log('uploadSuccess',file,response)
            if(response.code=1){
                lvideoUrl=response.data
                $("#uploadvideo").html('<video height="200" src=" '+lvideoUrl+'" controls="controls"></video>')
                $(".video-msg").text("上传成功")
                roomVideo.destroy();
                initWebuploader();
                // $("#btn-result").show()
            }else {
                $(".video-msg").text("上传失败")
            }


        });
        roomVideo.on( 'uploadError', function( file ) {
            // console.log('uploadError')
            lvideoUrl="";
            $(".video-msg").text("上传失败")
        });

        roomVideo.on( 'uploadProgress', function( file, percentage ) {
            // console.log('uploadProgress')
        });
    }
    function initWebuploaderImg() {
        var roomVideo = WebUploader.create({

            // 选完文件后，是否自动上传。
            auto: true,

            // swf文件路径
            swf: '/js/Uploader.swf',

            // 文件接收服务端。
            server: '/file/upload',
            fileNumLimit: 2,
            duplicate:true,
            chunked: true,
            chunkSize: 2 * 1024 * 1024,
            threads: 1,
            pick: {
                id: '#picture-url',
                label: '上传图片'
            },
            accept: {
                title: '上传图片',
                extensions: 'jpg,jpeg,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            }
        });


        roomVideo.on( 'fileQueued', function( file ) {
            // console.log('fileQueued')
            $(".picture-msg").text("加入文件")
        })

        roomVideo.on( 'uploadSuccess', function( file ,response) {
            // console.log('uploadSuccess',file,response)
            if(response.code=1){
                screenShot=response.data
                $("#uploadpicture").html('<img height="200" src=" '+screenShot+'" />')
                $(".picture-msg").text("上传成功")
                roomVideo.destroy();
                initWebuploaderImg();
                // $("#btn-result").show()
            }else {
                $(".picture-msg").text("上传失败")
            }


        });
        roomVideo.on( 'uploadError', function( file ) {
            // console.log('uploadError')
            screenShot="";
            $(".picture-msg").text("上传失败")
        });

        roomVideo.on( 'uploadProgress', function( file, percentage ) {
            // console.log('uploadProgress')
        });
    }
    initWebuploader();
    initWebuploaderImg();

    function renderPkp() {
        var p =["a","b","c","d"]
        var shtml ="";
        for(var i=0; i<p.length; i++){
            shtml+='<ul class="clearfix">'
            for(var j=1; j<14; j++){
                shtml+='<li data-pkp="'+ p[i]+j +'"><img src="/res/images/pkp/'+ (p[i]+j)+'.png"></li>'
            }
            shtml+='</ul>'
        }

        return shtml;
    }

    var selectPkpZ=[] //庄
    var selectPkpX=[] //闲

    function deleArr(param) {

        for(var k=0; k<selectPkpZ.length; k++){
            if(selectPkpZ[k] == param){
                selectPkpZ.splice(k,1)
                return
            }
        }

        for(var n=0; n<selectPkpX.length; n++){
            if(selectPkpX[n] == param){
                selectPkpX.splice(n,1)
                return
            }
        }
    }

    function renderSelectPkp(z,x) {
        var hstrZ ="";
        var hstrX ="";

        for(var i=0; i<z.length; i++){
            hstrZ+='<li data-pkp="'+ z[i] +'"><img src="/res/images/pkp/'+ z[i]+'.png"></li>'
        }

        for(var j=0; j<x.length; j++){
            hstrX+='<li data-pkp="'+ x[j] +'"><img src="/res/images/pkp/'+ x[j]+'.png"></li>'
        }


        $("#select-pkp-z").html(hstrZ)
        $("#select-pkp-x").html(hstrX)
    }

    function clearAll() {
         selectPkpZ=[]
         selectPkpX=[]
        $("#pkp").find("li").removeClass("act");
         $(".video-msg").empty()
         $("#uploadvideo").empty()
        $("#select-pkp-z").empty()
        $("#select-pkp-x").empty()
    }


    pkp(function () {
        renderSelectPkp(selectPkpZ,selectPkpX)
        console.log("庄",selectPkpZ)
        console.log("闲",selectPkpX)
    })
    
    function duibi(val) {
        var selectPkp = selectPkpZ.concat(selectPkpX)
        var arr = []

        for(var i =0; i<selectPkp.length; i++){
            if(selectPkp[i] == val){
                arr.push(selectPkp[i])
            }
        }
        console.log(arr)
        return arr;

    }
    function pkp(callback) {
        $("#pkp").html(renderPkp()).find("li").off("click").on("click",function () {
            var $self=$(this)
            /*if($(this).hasClass("act")){
                deleArr($(this).attr("data-pkp"))
                $(this).removeClass("act")
                callback()
            }else { }*/

                $.rootOpenDialog({
                    btn:["庄","闲"],
                    yes:function (i) {

                        if(duibi($self.attr("data-pkp")).length < 8){
                            selectPkpZ.push($self.attr("data-pkp"))
                            // $self.addClass("act")
                            layer.close(i)
                            callback()
                        }else {
                            $.rootErrorDialog("最多只能选择八张",3000)
                        }


                    },
                    btn2:function (i) {

                        if(duibi($self.attr("data-pkp")).length < 8){
                            selectPkpX.push($self.attr("data-pkp"))
                            // $self.addClass("act")
                            layer.close(i)
                            callback()
                        }else {
                            $.rootErrorDialog("最多只能选择八张",3000)
                        }

                    },
                    area:200,
                    content:'<div style="text-align: center">选择庄/闲</div>',
                    closeBtn:false,
                    shadeClose:true
                })




        });
    }

    $("#select-pkp-z,#select-pkp-x").on("click","li",function () {
        var o = $(this).attr("data-pkp")
        deleArr(o)
        $(this).remove()

        $("#pkp").find('li[data-pkp="'+ o +'"]').removeClass("act")

        console.log("庄",selectPkpZ)
        console.log("闲",selectPkpX)
    })




    $("#btn-result").on("click",function () {
        // console.log($("#paizi").find("input[name='paizi']:checked").val())
        // if(!$("#paizi").find("input[name='paizi']:checked").val()){
        //     $.rootErrorDialog("请选庄闲和",3000)
        //     return
        // }
        if(selectPkpZ.length == 0 || selectPkpX.length == 0){
            $.rootErrorDialog("请填写结果",3000)
            return
        }
        if(lvideoUrl == ""){
            $.rootErrorDialog("请上传视频",3000)
            return
        }

        var openCode = {
            "z" : selectPkpZ,
            "x" : selectPkpX
        };

        var index = layer.load(0);
        //doGetOpenTime()
        $.restPost('/lottery/doInsert',{
            token:window.localStorage.getItem('token'),
            openCode:JSON.stringify(openCode),
            videoUrl:lvideoUrl,
            roomId:$.getUrlLocation(),
            screenShot:screenShot
            // winner:$("#paizi").find("input[name='paizi']:checked").val()
        }).done(function (msg, data) {
            layer.close(index)
            clearAll()
            lvideoUrl=""
            screenShot=""
            pageInit({
                pageNum: 1,
                pageSize:10,
                token: window.localStorage.getItem('token')
            })

            $.rootSuccessDialog("成功",2000)
        }).fail(function (msg) {
            layer.close(index)
            $.rootErrorDialog("失败",2000)
        })
    })

    function roomLottery(list) {
        var str = '';
        for(var i=0; i<list.length; i++){
            str+=  '<div class="panel ">'+
                '<div class="panel-heading">'+
                '<div class="panel-btns">'+
                '<a class="minimize maximize">+</a>'+
                '</div>'+
                '<h4  class="panel-title">第'+(parseInt(list[i].issue))+'期</h4>'+

                '</div>'+
                '<div class="panel-body" style="display: none">' +
                '<div class="col-sm-12">' +
                '<span>视频：</span><video style="vertical-align: middle;" height="200" src="'+list[i].videoUrl+'" controls="controls"></video></div>'+
                '<div class="col-sm-12">' +
                '<span>截图：</span><img width="80%" height="500" src="' + list[i].screenShot + '"/>' +
                '</div>'+
                '<div class="col-sm-12">' +
                '<span>开奖：</span><img width="80%" src="' + list[i].imgUrl + '"/>' +
                '</div>'+
                '<div class="col-sm-12">' +
                '<span>赢家：</span><span>'+getChWinner(list[i].winner)+'</span>' +
                '</div>'+
                '<div class="col-sm-12">' +
                '<span>开奖时间：</span><span>'+(new Date(list[i].createTime)).format("yyyy-MM-dd hh:mm:ss")+'</span>' +
                '</div>'+
                '</div>'+
                '</div>'
        }

        return str
    }

    function getChWinner(winner){
        if(winner == 'z')
            return '庄';
        if(winner == 'x')
            return '闲';
        if(winner == 'zd')
            return '庄对';
        if(winner == 'xd')
            return '闲对';
        if(winner == 'h')
            return '和';
        else
            return '暂无';
    }

    function pageInit(requestData) {
        $.restPost('/lottery/doPageQuery',requestData).done(function (msg,data) {

            $("#lotterylsit").html(roomLottery(data.list))
            laypage({
                cont: 'page', //容器。
                pages: data.pages, //通过后台拿到的总页数
                curr: requestData.pageNum || 1, //当前页
                skip: true, //是否开启跳页
                skin: 'molv', //皮肤,
                jump: function (obj, first) { //触发分页后的回调
                    requestData.pageNum = obj.curr;
                    if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                        pageInit(requestData);
                    }
                }
            });

            jQuery('.minimize').off("click").on("click",function(e){
                e.preventDefault();
                var t = jQuery(this);
                var p = t.closest('.panel');
                if(!jQuery(this).hasClass('maximize')) {
                    p.find('.panel-body, .panel-footer').slideUp(200);
                    t.addClass('maximize');
                    t.html('&plus;');
                } else {
                    p.find('.panel-body, .panel-footer').slideDown(200);
                    t.removeClass('maximize');
                    t.html('&minus;');
                }
                return false;
            });

        })
    }
    pageInit({
        pageNum: 1,
        pageSize:10,
        token: window.localStorage.getItem('token'),
        roomId:$.getUrlLocation()
    })


    $.restPost("/room/doSelect",{ token: window.localStorage.getItem('token'),id:$.getUrlLocation()}).done(function (msg,res) {
        // console.log(res)
        $("#roomname").text(res.title)
    })
    var dshtimer

    function doGetOpenTime() {
        clearInterval(dshtimer)
        $.restPost("/lottery/doGetOpenTime",{ token: window.localStorage.getItem('token'),roomId:$.getUrlLocation()}).done(function (msg,res) {
            console.log( new Date(res.endTime).getTime(), new Date(res.enterTime).getTime())
            var s= (new Date(res.endTime).getTime()-new Date(res.enterTime).getTime())/1000
            dshtimer=setInterval(function () {
                var _s=s--;
                if(_s == 0){
                    $("#djs").text("开奖中...")
                    clearInterval(dshtimer)

                }else{
                    $("#djs").text(_s+'秒')
                }

            },1000)



        })
    }
    //doGetOpenTime()

})